/* eslint-disable @typescript-eslint/ban-ts-comment */
import React, { useEffect, useState } from 'react';
import Strings from '@/i18n';
import { useProps } from '@ray-js/panel-sdk';
import { publishDps, router, showToast, Text, View } from '@ray-js/ray';
import { NavBarCustom } from '@/components/NavBarCustom';
import { Checkbox, Tag } from '@ray-js/smart-ui';
import clsx from 'clsx';
import { useSelector } from 'react-redux';
import { ReduxState } from '@/redux';
import { useSwitchInfo } from '@/hooks/useSwitchInfo';
import { useWaterControlInfo } from '@/hooks/useWaterControlInfo';
import styles from './index.module.less';

export const decodeArea = (area: string) => {
  // 将十六进制字符串转换为8位二进制字符串
  const binary = parseInt(area, 16).toString(2).padStart(5, '0');
  return binary.split('').reverse().join('');
};

// 添加encodeArea方法，将8位二进制字符串转换为十六进制字符串
export const encodeArea = (binary: string) => {
  // 将二进制字符串转换为2位十六进制字符串
  return parseInt(binary, 2).toString(16).padStart(2, '0');
};

const Area: React.FC = () => {
  const { irrigation_area: irrigationArea } = useProps();

  const area = irrigationArea?.length === 2 ? decodeArea(irrigationArea) : '11111';

  const dps = useWaterControlInfo();

  const waterDps = ['countdown_1', 'countdown_3', 'countdown_5', 'usb_countdown_1', 'countdown_9'];

  const showDevie = waterDps.map(item => {
    const res = dps.find(group => group.water.timerDpName === item);
    return res.water;
  }).filter(item => !item.hide && !item.isOffLine);

  const [isAll, setIsAll] = React.useState(area === '11111');

  const [diy, setDiy] = useState<('0' | '1')[]>(area.split(''));

  const handlerSave = () => {
    if (isAll) {
      publishDps({
        irrigation_area: '1f',
      });
      showToast({
        title: Strings.getLang('save_success'),
      });
      router.back();
      return;
    }
    if (diy.every(item => `${item}` === '0')) {
      showToast({
        title: Strings.getLang('noSelectTip'),
        icon: 'none',
      });
      return;
    }

    const newDiy = [...diy].reverse();
    publishDps({
      irrigation_area: encodeArea(newDiy.join('')),
    });
    showToast({
      title: Strings.getLang('save_success'),
    });
    router.back();
  };

  return (
    <View className={styles.view}>
      <NavBarCustom name={Strings.getLang('irrigation_area')} back />
      <View className={styles.content}>
        <View className={styles.topBox}>
          <View className={styles.option}>
            <Checkbox value={isAll} onChange={value => setIsAll(true)}>
              {Strings.getLang('allArea')}
            </Checkbox>
          </View>
          <View className={styles.option}>
            <Checkbox value={!isAll} onChange={value => setIsAll(false)}>
              {Strings.getLang('diyArea')}
            </Checkbox>
          </View>
        </View>

        {!isAll ? (
          <View className={styles.optionBox}>
            <View className={styles.diyAreaTip}>
              <Text>{Strings.getLang('diyAreaTip')}</Text>
            </View>

            <View className={styles.optionBox}>
              {showDevie.map((item, index) => {
                return (
                  <View
                    className={clsx(styles.option, styles.optionBot,  (item.hide || item.isOffLine) && styles.hide)}
                    key={item.dpId}
                  >
                    <Checkbox
                      value={diy[index].toString() === '1'}
                      onChange={event => {
                        diy[index] = event.detail ? 1 : 0;
                        setDiy([...diy]);
                      }}
                      disabled={item.hide}
                    >
                      {`${item?.name}`}
                    </Checkbox>
                    {item.hide ? <Tag type="danger">已删除</Tag> : <View />}
                  </View>
                );
              })}
            </View>
          </View>
        ) : null}
        <View className={clsx(styles.saveBtn)} onClick={handlerSave}>
          <Text>{Strings.getLang('save')}</Text>
        </View>
      </View>
    </View>
  );
};

export default Area;
